package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.config.LocalUserId;
import com.fwtai.service.ServiceCouponArea;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.web.GoodsAreaDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 区域商品库存业务层
 * @作者 李宇鹏
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2023-04-18 09:19:30
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class GoodsAreaService{

  private final GoodsAreaDao goodsAreaDao;

  private final ServiceCouponArea serviceCouponArea;

  private final ThreadPoolTaskExecutor taskExecutor;

  public GoodsAreaService(final GoodsAreaDao goodsAreaDao,final ServiceCouponArea serviceCouponArea,final ThreadPoolTaskExecutor taskExecutor){
    this.goodsAreaDao = goodsAreaDao;
    this.serviceCouponArea = serviceCouponArea;
    this.taskExecutor = taskExecutor;
  }

  public String add(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request);
      final String p_user_name = "user_name";
      final String validate = ToolClient.validateField(formData,p_user_name);
      if(validate != null){
        return validate;
      }
      final HashMap<String,Object> result = goodsAreaDao.getAreaUserId(formData.getString(p_user_name));
      return serviceCouponArea.addCoupon(result);
    },taskExecutor).join();
  }

  public String edit(final HttpServletRequest request){
    final Long loginKey = LocalUserId.getLong();
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request);
      final String p_kid = "kid";
      final String p_inventory = "inventory";
      final String p_goodsId = "goodsId";
      final String validate = ToolClient.validateField(formData,p_kid,p_inventory,p_goodsId);
      if(validate != null){
        return validate;
      }
      final String fieldInteger = ToolClient.validateInteger(formData,p_inventory);
      if(fieldInteger != null){
        return fieldInteger;
      }
      final Integer v_inventory = formData.getInteger(p_inventory);
      if(v_inventory == null){
        return ToolClient.createJsonFail("库存不是有效的数字");
      }else{
        formData.put(p_inventory,v_inventory);
      }
      final long kid = formData.getLong(p_kid);
      final Long v = goodsAreaDao.queryExistById(kid);
      if(v == null){
        return ToolClient.createJsonFail("数据不存在,刷新重试");
      }
      final HashMap<String,Object> hashMap = goodsAreaDao.getGoodAreaInventory(kid);
      formData.put(p_kid,kid);
      formData.remove(p_goodsId);
      final HashMap<String,Object> map = new HashMap<>(6);
      handlerLog(map,loginKey,kid,v_inventory);
      handlerLog(map,hashMap);
      return ToolClient.executeRows(goodsAreaDao.edit(formData,map));
    },taskExecutor).join();
  }

  /**返回第一个参数*/
  public void handlerLog(final HashMap<String,Object> map,final HashMap<String,Object> hashMap){
    map.put("original",hashMap.get("original"));//原始值（修改之前的库存量）
    map.put("coupon",hashMap.get("coupon"));
  }

  /**
   * 组装参数,然后调用 goodsAreaDao.addLogRecord(map);直接添加
   * @param loginKey 登录人的kid
   * @param goods_area_kid 记录id（goods_area.kid）
   * @param inventory 库存新值（修改之后的库存量）
   * @作者 田应平
   * @QQ 444141300
   * @创建时间 2024/1/16 15:57
  */
  public void handlerLog(final HashMap<String,Object> map,final long loginKey,final long goods_area_kid,final int inventory){
    map.put("kid",new IdBuilder().getId121L());
    map.put("operator",loginKey);
    map.put("goods_area_kid",goods_area_kid);
    map.put("new_value",inventory);
  }

  public String queryById(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      return ToolClient.queryJson(goodsAreaDao.queryById(kid));
    },taskExecutor).join();
  }

  public String getRecord(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      return ToolClient.queryJson(goodsAreaDao.getRecord(kid));
    },taskExecutor).join();
  }

  public String listData(final PageFormData formData){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> goodsAreaDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> goodsAreaDao.getListTotal(formData),taskExecutor);
        return ToolClient.dataTableOK(listData.join(),listTotal.join());
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }

  //获取表goods_area的字段goods_id的下拉框列动态值选项的数据
  public String getGoods_id(){
    return CompletableFuture.supplyAsync(()->ToolClient.queryJson(goodsAreaDao.getGoods_id()),taskExecutor).join();
  }

  //获取表goods_area的字段user_id的下拉框列动态值选项的数据
  public String getUser_id(){
    return CompletableFuture.supplyAsync(()->ToolClient.queryJson(goodsAreaDao.getUser_id()),taskExecutor).join();
  }
}